package com.daocao.common.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.daocao.common.constants.HttpStatus;
import com.daocao.common.entity.dto.LoginDto;
import com.daocao.common.entity.vo.LoginUserVo;
import com.daocao.common.exception.ServiceException;
import com.daocao.common.service.AuthService;
import com.daocao.common.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    private final AuthenticationManager authenticationManager;
    private final JwtUtils jwtUtils;

    public AuthServiceImpl(AuthenticationManager authenticationManager, JwtUtils jwtUtils) {
        this.authenticationManager = authenticationManager;
        this.jwtUtils = jwtUtils;
    }

    @Override
    public String login(LoginDto loginDto) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginDto.getAccount(), loginDto.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        LoginUserVo loginUser = (LoginUserVo) authenticate.getPrincipal();
        if (ObjectUtil.isNull(loginUser)) {
            throw new ServiceException(HttpStatus.UNAUTHORIZED, "认证失败");
        }
        return jwtUtils.createToken(loginUser);
    }
}
